package plus.lgx.textsearcher.searcher.extender;

import plus.lgx.textsearcher.config.SearcherConfig;

/**
 * Class name: GreedyExtender
 *
 * Create time: 12/17/22 8:26 PM
 *
 * @author lgx
 * @version 1.0
 */
public class GreedyExtender extends Extender {

    public GreedyExtender(SearcherConfig config) {
        super(config);
    }

    private final int maxExtendCharsCount = config.maxExtendCharsCount;
    private final int len = config.searchContent.length();
    private final char[][] DELIMITER = config.DELIMITER;

    @Override
    public String extend() {
        int beginInd = Math.max(index.get() - 1, 0), bi = beginInd;
        int endInd   = Math.min(index.get() + (m == null ? len : m.end() - m.start()), off - 1), ei = endInd;
        char b, e;

        for(b = content.charAt(beginInd);
            beginInd > 0 && index.get() - beginInd < maxExtendCharsCount;
            b = content.charAt(--beginInd))
            for (char[] chs : DELIMITER)
                for (char c : chs) if (b == c) {
                    bi = beginInd;
                    if (chs != DELIMITER[1])  // this if condition makes extended string contains left bracket
                        bi++;
                }

        for(e = content.charAt(endInd);
            endInd < off - 1 && endInd - index.get() < maxExtendCharsCount;
            e = content.charAt(++endInd))
            for (char[] chs : DELIMITER)
                for (char c : chs) if (e == c) {
                    ei = endInd;
                    if (chs != DELIMITER[2])  // this if condition makes extended string contain right bracket
                        ei--;
                }

        index.set(Math.min(endInd, off - 1));
        return content.substring(bi, Math.min(ei, off)).trim();
    }

}
